import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store'
import { Message } from 'element-ui'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    component: () => import('@/views/layout'),
    redirect: '/welcome',
    children: [
      { path: '/welcome', component: () => import('@/views/welcome') },
      { path: '/categories', component: () => import('@/views/categories') },
      { path: '/goods', component: () => import('@/views/goods') },
      { path: '/orders', component: () => import('@/views/orders') },
      { path: '/params', component: () => import('@/views/params') },
      { path: '/reports', component: () => import('@/views/reports') },
      { path: '/roles', component: () => import('@/views/roles') },
      { path: '/users', component: () => import('@/views/users') }
    ]
  },
  { path: '/login', component: () => import('@/views/login') }
]

const router = new VueRouter({
  routes
})

// 导航守卫
const writeList = ['/login']
router.beforeEach((to, from, next) => {
  const token = store.state.user.token
  if (token) {
    next()
  } else {
    if (writeList.includes(to.path)) {
      next()
    } else {
      next('/login')
      // 给用户一个提示 this.$message()
      Message.warning('您还未登录, 请先登录哦')
    }
  }
})

export default router
